package com.sunda.spmsweb.ibmmq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunda.spmswms.service.ICostCenterService;
import com.sunda.spmswms.service.IWerksService;
import com.sunda.spmswms.service.IWhsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsOperations;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.TextMessage;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @program: ibmmq
 * @description: ReceiveMessage
 * @author: Wayne Wu
 * @create: 2020-07-14 13:30
 **/

//消息消费者的类上必须加上@Component，或者是@Service，这样的话，消息消费者类就会被委派给Listener类，原理类似于使用SessionAwareMessageListener以及MessageListenerAdapter来实现消息驱动POJO
@Component
@Slf4j
public class ReceiveMessage extends MessageListenerAdapter {
    @Autowired
    @Qualifier(value = "PIN_IN3")
    JmsOperations jmsOperations;

    @Autowired
    IWerksService iWerksService;

    @Autowired
    IWhsService iWhsService;

    @Autowired
    ICostCenterService iCostCenterService;

    /** 注释此行即不再监听消息队列 */
    //@Override
    //@JmsListener(destination = JmsConfigIn.queue)
    public void onMessage(Message message) {
        try {
            log.info("\n\n========= 准备接收监听数据......");
            String messageBody = ((TextMessage)message).getText();
            //System.out.println("\n\n\n messageBody === \n\n\n" + messageBody.substring(0,1000) + "\n\n\n");

            JSONObject jsonObject = JSONObject.parseObject(messageBody);
            String REQUEST = jsonObject.getString("REQUEST");
            String RequestData = JSONObject.parseObject(REQUEST).getString("RequestData");
            String Data = JSONObject.parseObject(RequestData).getString("Data");

            String parseData = StringEscapeUtils.unescapeJavaScript(Data);
            //String parseData = JSON.parse(Data).toString();

            String parseDataEncode = new String(parseData.getBytes("ISO-8859-1"), "utf-8");
            System.out.println("\n\nparseDataEncode ==== " + parseDataEncode);

            /** 获取到的数据，部分信息携带四层 或 三层双引号，
             * 转换 JSONObject 会报格式错误，需强制替换处理
             * ["GF03","GF0330601",""""加纳陶瓷干燥工作中心K1,K2"""]
             * */
            parseDataEncode = parseDataEncode
                    .replace("\"\"\"\"", "\"")
                    .replace("\"\"\"", "\"");

            JSONObject doc = JSONObject.parseObject(parseDataEncode);


            /** 监听来自 SAP 的公司工厂数据，写入/更新数据库 */
            if (doc.containsKey("Z_SPMS_GETFACTORY_IT_WERKS")){
                iWerksService.insertWerks(doc);
            }

            /** 监听来自 SAP 的仓库信息数据，写入/更新数据库 */
            if (doc.containsKey("Z_SPMS_GETWAREHOUSE_IT_LGORT")){
                iWhsService.insertWhs(doc);
            }

            /** 监听来自 SAP 的成本中心数据，写入/更新数据库 */
            if (doc.containsKey("Z_SPMS_GETCOSTCENTER_IT_CSKS")){
                iCostCenterService.insertCostCenter(doc);
            }


            if (doc.containsKey("Z_RFC_STORE_09_IT_ZCREDIT")){
                JSONArray array = doc.getJSONArray("Z_RFC_STORE_09_IT_ZCREDIT");
                for(int i = 0; i<array.size() && i < 5; i++){
                    System.out.println(array.size() + "    " + i + "   同步客户信用    Z_RFC_STORE_09_IT_ZCREDIT    " + array.get(i).toString());
                }
            }

            if (doc.containsKey("Z_RFC_STORE_03_IT_TVKO")){
                JSONArray array = doc.getJSONArray("Z_RFC_STORE_03_IT_TVKO");
                for(int i = 0; i<array.size() && i < 10; i++){
                    System.out.println(array.size() + "    " + i + "   组织机构码表接口    Z_RFC_STORE_03_IT_TVKO    " + array.get(i).toString());
                }
            }

            if (doc.containsKey("Z_RFC_STORE_01_IT_MAKT")){
                JSONArray array6 = doc.getJSONArray("Z_RFC_STORE_01_IT_MAKT");
                for(int i = 0; i < array6.size(); i++){
                    System.out.println("array6.getJSONArray(i) ==== " + array6.getJSONArray(i));
                    if (array6.getJSONArray(i).get(3).toString().equals("1")){
                        //writeFile("/Users/waynewu/Desktop/material.txt", array6.get(i).toString());
                        System.out.println(array6.size() + "    " + i + "    物料主数据   Z_RFC_STORE_01_IT_MAKT    " + array6.get(i).toString());
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            log.info("========= 监听异常 ========" + e);
        }
    }


    /**
     * 将数据直接追加写入输出到指定文件
     * @param fileFullPath
     * @param content
     */
    public static void writeFile(String fileFullPath,String content) {
        FileOutputStream fos = null;
        try {
            //true不覆盖已有内容
            fos = new FileOutputStream(fileFullPath, true);
            //写入
            fos.write(content.getBytes());
            // 写入一个换行
            fos.write("\r\n".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fos != null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}